class Article < ActiveRecord::Base
  include TrinitGuid
  
  belongs_to :user
  belongs_to :blog
  has_many :comments, :order => 'published_at DESC'
  has_and_belongs_to_many :tags, :foreign_key => 'article_id'
  
  before_create :set_defaults, :create_guid
  before_save :set_published_date, :keywords_to_tags
  
  validates_presence_of :title
  
  def add_comment(options)
    comments.build(options)
  end
  
  protected
  
  def set_defaults
    
  end
  
  def set_published_date
    self[:published_at] = Time.now if self[:published_at] == nil
  end
  
  def keywords_to_tags
    Article.transaction do
      tags.clear
      #handle chinese comma.
      tag_string = keywords.to_s.gsub('，',',')
      tag_string.scan(/(([,]).*?\2|[\.\w]+)/).collect do |k|
        puts k.first
        k.first.tr(',', '')
      end.uniq.each do |t|
        tags << Tag.get(t)
      end
    end
  end
end
